﻿/*
*VMukti -- An open source video conferencing platform.
*
* Copyright (C) 2007 - 2008, VMukti Solutions Pvt. Ltd.
*
* Hardik Sanghvi <hardik@vmukti.com>
*
* See http://www.vmukti.com for more information about
* the VMukti project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, forums and mailing lists
* for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Media;
using VMukti.Business;
using VMukti.ZipUnzip.Zip;
using VMuktiAPI;

namespace VMukti.Presentation.Controls.UploadModule
{
    public class clsModulePermission
    {
        public int ModuleID = -1;
        public int PermissionID = -1;
        public string PermissionName = "";
        public int PermissionValue = -1;

        public clsModulePermission()
        {
        }

        public clsModulePermission(int pModuleID, int pPermissionID, string pPermissionName, int pPermissionValue)
        {
            try
            {
                this.ModuleID = pModuleID;
                this.PermissionID = pPermissionID;
                this.PermissionName = pPermissionName;
                this.PermissionValue = pPermissionValue;
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "clsModulePermission()--:--clsModulePermission.xaml.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);

            }
        }
    }

    /// <summary>
    /// Interaction logic for CtlUploadModule.xaml
    /// </summary>
    public partial class CtlUploadModule : System.Windows.Controls.UserControl,IDisposable
    {
        List<clsModulePermission> objModulePermissions = new List<clsModulePermission>();

        OpenFileDialog ofd = new OpenFileDialog();
        Assembly ass = null;
        Assembly a = null;
        DirectoryInfo di;
        ArrayList al = new ArrayList();
        Type[] typecontrol;
        List<string> strValues = new List<string>();
        List<Assembly> lstAss = new List<Assembly>();

        public CtlUploadModule()
        {
            try
            {
                InitializeComponent();
                ass = Assembly.GetAssembly(typeof(CtlUploadModule));
                btnUpload.Click += new RoutedEventHandler(btnUpload_Click);
                btnSubmit.Click += new RoutedEventHandler(btnSubmit_Click);
                btnCancel.Click += new RoutedEventHandler(btnCancel_Click);
                cmbAssembly.SelectionChanged += new SelectionChangedEventHandler(cmbAssembly_SelectionChanged);
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "CtlUploadModule()--:--CtlUploadModule.xaml.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);

            }
        }

        void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                txtUpload.Clear();
                txtZip.Clear();
                cmbAssembly.Items.Clear();
                cmbClass.Items.Clear();
                txtModule.Clear();
                txtVersion.Clear();
                rtbDescription.SelectAll();
                rtbDescription.Selection.Text = "";
                ckbCollaborate.IsChecked = false;
                ckbAuthentication.IsChecked = false;
                if (grid1.Children.Count > 0)
                {
                    grid1.Children.Clear();
                }

            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "CtlUploadModule()--:--CtlUploadModule.xaml.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);

            }
        }

        void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ofd.FileName != null && ofd.FileName != "")
                {
                    if (cmbAssembly.SelectedItem != null)
                    {
                        if (cmbClass.SelectedItem != null)
                        {
                            if (txtModule.Text != "" && txtModule.Text != null)
                            {
                                if (!new ClsModuleLogic().ModuleExists(txtModule.Text))
                                {
                                    System.Windows.MessageBox.Show("Specify another module name");
                                }
                                else
                                {
                                    try
                                    {
                                        WebClient wc = new WebClient();
                                        wc.Credentials = new NetworkCredential("adiance", "adiance");
                                        wc.UploadFile("ftp://" + VMuktiAPI.VMuktiInfo.BootStrapIPs[0] + "/VMukti" + "/" + ofd.SafeFileName, ofd.FileName);
                                    }
                                    catch (Exception ex)
                                    {
                                        ex.Data.Add("My Key", "CtlUploadModule()--:--CtlUploadModule.cs--:--" + ex.Message + " :--:--");
                                        ClsException.LogError(ex);
                                        ClsException.WriteToErrorLogFile(ex);

                                    }

                                    ClsModuleLogic cml = new ClsModuleLogic();
                                    TextRange tr = new TextRange(rtbDescription.Document.ContentStart, rtbDescription.Document.ContentEnd);
                                    int intModId = cml.AddModule(-1, txtModule.Text, txtVersion.Text, tr.Text, ((ComboBoxItem)cmbAssembly.SelectedItem).Content.ToString(), ((ComboBoxItem)cmbClass.SelectedItem).Content.ToString(), txtZip.Text, 1, ckbCollaborate.IsChecked.Value, ckbAuthentication.IsChecked.Value);
                                    ClsPermissionLogic cpl = new ClsPermissionLogic();

                                    foreach (object chk in grid1.Children)
                                    {
                                        if (chk.GetType() == typeof(System.Windows.Controls.CheckBox) && ((System.Windows.Controls.CheckBox)chk).Tag != null)
                                        {
                                            int i = 0;
                                            string[] strPermission = (((System.Windows.Controls.CheckBox)chk).Tag).ToString().Split(',');

                                            for (i = 0; i < objModulePermissions.Count; i++)
                                            {
                                                if (objModulePermissions[i].PermissionName == strPermission[0])
                                                {
                                                    break;
                                                }
                                            }
                                            if (i == objModulePermissions.Count)
                                            {
                                                objModulePermissions.Add(new clsModulePermission(intModId, cpl.Add_Permission(-1, intModId, strPermission[0], int.Parse(strPermission[1])), strPermission[0], int.Parse(strPermission[1])));
                                            }

                                            if (((System.Windows.Controls.CheckBox)chk).IsChecked == true)
                                            {
                                                for (int j = 0; j < objModulePermissions.Count; j++)
                                                {
                                                    if (objModulePermissions[j].PermissionName == strPermission[0])
                                                    {
                                                        cpl.Add_ModulePermission(objModulePermissions[j].PermissionID, int.Parse(strPermission[2]));
                                                        ((System.Windows.Controls.CheckBox)chk).IsChecked = false;

                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    System.Windows.MessageBox.Show("Module Uploaded");

                                    txtUpload.Clear();
                                    txtZip.Clear();
                                    cmbAssembly.Items.Clear();
                                    cmbClass.Items.Clear();
                                    txtModule.Clear();
                                    txtVersion.Clear();
                                    ckbCollaborate.IsChecked = false;
                                    rtbDescription.SelectAll();
                                    rtbDescription.Selection.Text = "";
                                    ckbAuthentication.IsChecked = false;
                                    if (grid1.Children.Count > 0)
                                    {
                                        grid1.Children.Clear();
                                    }

                                    objModulePermissions.Clear();
                                }
                            }
                            else
                            {
                                System.Windows.MessageBox.Show("Enter Module Name");
                            }
                        }
                        else
                        {
                            System.Windows.MessageBox.Show("Select the Class Name");
                        }
                    }
                    else
                    {
                        System.Windows.MessageBox.Show("Select the Assembly File");
                    }
                }
                else
                {
                    System.Windows.MessageBox.Show("Browse the File to Upload");
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "btnSubmit_Click()--:--CtlUploadModule.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!Directory.Exists(ass.Location.Replace("VMukti.Presentation.exe", @"Temp")))
                {
                    di = Directory.CreateDirectory(ass.Location.Replace("VMukti.Presentation.exe", @"Temp"));
                }
                else
                {
                    di = new DirectoryInfo(ass.Location.Replace("VMukti.Presentation.exe", @"Temp"));
                }

                DirectoryInfo[] dinew = di.GetDirectories();

                for (int i = 0; i < dinew.Length; i++)
                {
                    dinew[i].Delete(true);
                }

                ofd.Filter = "Zip Files|*.zip";

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    FastZip fz = new FastZip();
                    fz.ExtractZip(ofd.FileName, di.FullName, null);

                    txtUpload.Text = ofd.FileName;
                    txtZip.Text = ofd.SafeFileName;

                    DirectoryInfo[] diSub = di.GetDirectories()[0].GetDirectories();

                    for (int m = 0; m < diSub.Length; m++)
                    {
                        if (diSub[m].Name.ToLower() == "control")
                        {
                            ShowDirectory(diSub[m]);
                            break;
                        }
                    }

                    for (int j = 0; j < al.Count; j++)
                    {
                        using (FileStream fs = File.Open(al[j].ToString(), FileMode.Open))
                        {
                            using (MemoryStream ms = new MemoryStream())
                            {
                                byte[] buffer = new byte[1024];
                                int read = 0;
                                while ((read = fs.Read(buffer, 0, 1024)) > 0)
                                    ms.Write(buffer, 0, read);
                                try
                                {
                                    a = Assembly.Load(ms.ToArray());
                                }
                                catch (Exception ex)
                                {
                                    ex.Data.Add("My Key", "btnUpload_Click()--:--CtlUploadModule.cs--:--" + ex.Message + " :--:--");
                                    ClsException.LogError(ex);
                                    ClsException.WriteToErrorLogFile(ex);
                                }
                            }
                        }

                        typecontrol = a.GetTypes();
                        for (int n = 0; n < typecontrol.Length; n++)
                        {
                            if (typecontrol[n].BaseType != null)
                            {
                                if (typecontrol[n].BaseType.Name.ToLower() == "usercontrol")
                                {
                                    int z = 0;
                                    for (z = 0; z < cmbAssembly.Items.Count; z++)
                                    {
                                        if (((ComboBoxItem)cmbAssembly.Items[z]).Content.ToString() == typecontrol[n].Module.ToString())
                                        {
                                            break;
                                        }
                                    }
                                    if (z == cmbAssembly.Items.Count)
                                    {
                                        ComboBoxItem cbiNew = new ComboBoxItem();
                                        lstAss.Add(a);
                                        cbiNew.Content = typecontrol[n].Module.ToString();
                                        cmbAssembly.Items.Add(cbiNew);
                                    }
                                    //break;
                                }
                                if (typecontrol[n].BaseType.Name.ToLower() == "enum")
                                {
                                    //lblPermissions.IsEnabled = true;
                                    if (typecontrol[n].Name == "ModulePermissions")
                                    {
                                        grid1.IsEnabled = true;
                                        scrollViewer1.IsEnabled = true;

                                        string[] str = Enum.GetNames(typecontrol[n]);


                                        for (int enumValues = 0; enumValues < typecontrol[n].GetFields().Length; enumValues++)
                                        {

                                            if (typecontrol[n].GetFields()[enumValues].FieldType.Name == "ModulePermissions")
                                            {
                                                strValues.Add(typecontrol[n].GetFields()[enumValues].GetRawConstantValue().ToString());
                                            }
                                        }

                                        ClsRoleCollection crc = ClsRoleCollection.GetAll();

                                        for (int i = 0; i < str.Length + 1; i++)
                                        {
                                            ColumnDefinition col = new ColumnDefinition();
                                            grid1.ColumnDefinitions.Add(col);
                                        }

                                        for (int roleCount = 0; roleCount < crc.Count + 1; roleCount++)
                                        {
                                            RowDefinition row = new RowDefinition();
                                            grid1.RowDefinitions.Add(row);
                                        }

                                        for (int k = 0; k < str.Length; k++)
                                        {
                                            System.Windows.Controls.Label l = new System.Windows.Controls.Label();
                                            l.Content = str[k];
                                            l.Background = Brushes.Snow;
                                            grid1.Children.Add(l);
                                            Grid.SetColumn(l, k + 1);
                                            Grid.SetRow(l, 0);
                                        }

                                        for (int r = 0; r < crc.Count; r++)
                                        {
                                            System.Windows.Controls.Label lRow = new System.Windows.Controls.Label();
                                            lRow.Content = crc[r].RoleName;
                                            lRow.Background = Brushes.Beige;
                                            grid1.Children.Add(lRow);
                                            Grid.SetColumn(lRow, 0);
                                            Grid.SetRow(lRow, r + 1);
                                        }

                                        for (int roleCount = 0; roleCount < crc.Count; roleCount++)
                                        {
                                            for (int perCount = 0; perCount < str.Length; perCount++)
                                            {
                                                System.Windows.Controls.CheckBox chk = new System.Windows.Controls.CheckBox();
                                                chk.Margin = new Thickness(5, 5, 0, 0);
                                                chk.Height = 14;
                                                chk.Width = 14;
                                                chk.Tag = str[perCount] + "," + strValues[perCount] + "," + crc[roleCount].ID;
                                                chk.BorderThickness = new Thickness(2, 2, 2, 2);
                                                grid1.Children.Add(chk);
                                                Grid.SetColumn(chk, perCount + 1);
                                                Grid.SetRow(chk, roleCount + 1);
                                            }
                                        }
                                        System.Windows.Controls.Label lblPermissions = new System.Windows.Controls.Label();
                                        lblPermissions.Height = 23;
                                        lblPermissions.Width = 80;
                                        lblPermissions.Content = "Permissions";
                                        grid1.Children.Add(lblPermissions);
                                        Grid.SetColumn(lblPermissions, 0);
                                        Grid.SetRow(lblPermissions, 0);

                                    }
                                }
                            }
                        }
                    }
                }
                al.Clear();
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "btnUpload_Click()--:--CtlUploadModule.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        void cmbAssembly_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (cmbAssembly.Items.Count > 0)
                {
                    for (int i = 0; i < lstAss.Count; i++)
                    {
                        if (lstAss[i].ManifestModule.ToString() == ((ComboBoxItem)cmbAssembly.SelectedItem).Content.ToString())
                        {
                            Type[] typeArr = lstAss[i].GetTypes();

                            for (int j = 0; j < typeArr.Length; j++)
                            {
                                if (typeArr[j].BaseType != null)
                                {
                                    if (typeArr[j].BaseType.Name.ToLower() == "usercontrol")
                                    {
                                        ComboBoxItem cbiNewClass = new ComboBoxItem();
                                        cbiNewClass.Content = typeArr[j].Name;
                                        cmbClass.Items.Add(cbiNewClass);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "cmbAssembly_SelectionChanged()--:--CtlUploadModule.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }

        public void ShowDirectory(DirectoryInfo dir)
        {
            try
            {
                foreach (FileInfo file in dir.GetFiles("*.dll"))
                {
                    int hj = al.Add(file.FullName);
                }
                foreach (DirectoryInfo subDir in dir.GetDirectories())
                {
                    ShowDirectory(subDir);
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "ShowDirectory()--:--CtlUploadModule.xaml.cs--:--" + ex.Message + " :--:--");
                ClsException.LogError(ex);
                ClsException.WriteToErrorLogFile(ex);
            }
        }





        #region IDisposable Members

        public void Dispose()
        {
            if (objModulePermissions != null)
            {
                objModulePermissions = null;
            }
            if (ofd != null)
            {
                ofd = null;
            }
            if (ass != null)
            {
                ass = null;
            }
            if (a != null)
            {
                a = null;
            }
            if (di != null)
            {
                di = null;
            }
            if (al != null)
            {
                al = null;
            }
            if (typecontrol != null)
            {
                typecontrol = null;
            }
            if (strValues != null)
            {
                strValues = null;
            }
            if (lstAss != null)
            {
                lstAss = null;
            }
        }

        #endregion

        ~CtlUploadModule()
        {
            Dispose();
        }
    }
}
